const express = require('express')
const cors = require('cors')
const { read, write } = require('./file')
const app = express()

app.use(cors())
app.use(express.json())
app.use(express.urlencoded({ extended: false }))

app.listen('3000', () => {
  console.log('http://localhost:3000')
})

app.get('/api/getbooks', async (req, res) => {
  const data = await read()
  console.log(data)
  res.send({
    status: 200,
    msg: '获取图书列表成功',
    data,
  })
})

app.post('/api/addbook', async (req, res) => {
  console.log(req.body)
  req.body.id = Date.now()
  const data = await read()
  data.unshift(req.body)
  await write(data)
  res.send({
    status: 201,
    msg: '添加图书成功！',
  })
})

app.get('/api/delbook', async (req, res) => {
  const { id } = req.query
  console.log('要删除的id', id)
  let data = await read()
  data = data.filter(item => item.id !== +id)
  await write(data)
  res.send({
    status: 200,
    msg: '删除图书成功',
  })
})
